package com.dx.mes.service.spc.service;

import com.dx.common.table.ppt.Bis_m_item;
import com.dx.common.table.ppt.Spc_mfg_data;
import com.dx.common.table.ppt.Spc_ret_mfg_data;
import com.dx.mes.common.bean.entity.UUIDObject;
import com.dx.mes.common.dao.IBisMItemDao;
import com.dx.mes.common.dao.ISpcMfgDataDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.service.spc.service.IFqprepdataService;
import com.dx.mes.service.spc.service.ISendToolInfoService;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtI;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtIA;
import com.dx.mes.service.spc.tx.Xpcmsdt.XpcmsrdtO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;

/**
 * Created by xxd on 2017/9/25.
 */
@Service("sendtoolInfoService")
public class SendtoolInfoService implements ISendToolInfoService {

    @Autowired
    private IBisMItemDao bisMItemDao;

    @Autowired
    private ISpcMfgDataDao spcMfgDataDao;

    @Autowired
    private IFqprepdataService fqprepdataService;

    //定时查表
    public void checkinfo() {
    /*    SELECT * FROM spc_ret_mfg_data  WHERE CONCAT(tool_id_fk, mes_id_fk) IN (
                SELECT DISTINCT CONCAT(tool_id_fk, mes_id_fk) FROM bis_m_item
        )
*/
//        String hql = "From Spc_mfg_data where input_flg == 0 ";
//        final List<Spc_mfg_data> spcMfgDataList = spcMfgDataDao.listBySQL(hql);
//
//        spcMfgDataList.stream().collect(Collectors.groupingBy(Spc_mfg_data::getTool_id));
//        final List<String> toolMesStringList = spcMfgDataList.stream().map(spcRetMfgData -> {
//            return spcRetMfgData.getTool_id() + "," + spcRetMfgData.getMes_id();
//        }).collect(Collectors.toList());

//        toolMesStringList.forEach(str->{
//            bisMItemDao.list()
//        });

        String hql = "From Spc_mfg_data where input_flg = 0 ";
        List<Spc_mfg_data> spcMfgDataList = spcMfgDataDao.find(hql);
        if (spcMfgDataList.size() > 0) {
            Map<String, List<List<String>>> toolMesMap = new HashMap<>();

            Set<String> keySet = new HashSet<>();
            for (int j = 0; j < spcMfgDataList.size(); j++) {
                Spc_mfg_data spc_mfg_data = spcMfgDataList.get(j);
                String toolId = spc_mfg_data.getTool_id();
                String mesId = spc_mfg_data.getMes_id();
                String key = toolId + ',' + mesId;
                keySet.add(key);
            }

            for (String s : keySet) {
                List<List<String>> totalValueList = new ArrayList<>();//一组key对应的所有list
                for (int i = 0; i < spcMfgDataList.size(); i++) {
                    List<String> valueList = new ArrayList<String>();//一组值
                    Spc_mfg_data spc_mfg_data = spcMfgDataList.get(i);
                    String toolId = spc_mfg_data.getTool_id();
                    String mesId = spc_mfg_data.getMes_id();
                    String key = toolId + ',' + mesId;
                    String dataValue = "";
                    for (int j = 0; j < 100; j++) {
                        dataValue = getDBDataValue(j, spc_mfg_data);
                        valueList.add(dataValue);
                    }
                    if (s.equals(key)) {
                        totalValueList.add(valueList);
                    }
                }
                System.out.print("------");
                toolMesMap.put(s, totalValueList);
            }


            for (Map.Entry<String, List<List<String>>> entry : toolMesMap.entrySet()) {
                XpcmsrdtI inTrx = new XpcmsrdtI();
                XpcmsrdtO xpcmsrdtO = new XpcmsrdtO();
                //Map.Entry<String, List<List<String>>> entry = (Map.Entry<String, List<List<String>>>) iter.next();
                String key = entry.getKey(); // toolid ,mesid
                List<List<String>> val = entry.getValue();//List<List<String>>
                String[] toolAndMes = key.split(",");
                //根据toolID\mes_id 查bis_m_item
                String hql2 = "From Bis_m_item where tool_id_fk = '" + toolAndMes[0] + "' and mes_id_fk = '" + toolAndMes[1] + "'";
                List<Bis_m_item> bis_m_items = bisMItemDao.find(hql2);
                for (int i = 0; i < val.size(); i++) {
                    List<String> valueList = val.get(i);
                    inTrx = bulidMessage2(bis_m_items, valueList, toolAndMes[0], toolAndMes[1]);
                    xpcmsrdtO = autoReportSPC(inTrx);//上报spc
                   /* if (xpcmsrdtO.getRtn_code().equals("0000000")) {
                        continue;
                    }*/
                }
            }
            //将input_flg置1
            for (int m = 0; m < spcMfgDataList.size(); m++) {
                Spc_mfg_data spc_mfg_data = spcMfgDataList.get(m);
                spc_mfg_data.setInput_flg(1);
                spcMfgDataDao.update(spc_mfg_data);
            }
        }

    }

    //上报spc
    private XpcmsrdtO autoReportSPC(XpcmsrdtI inTrx) {
        XpcmsrdtI xpcmsrdtI = inTrx;
        XpcmsrdtO xpcmsrdtO = new XpcmsrdtO();
        String strOutTrx = fqprepdataService.subMainProc(AppContext.getCurrEventNumber(),
                JacksonUtil.toJSONStr(xpcmsrdtI));
        xpcmsrdtO = JacksonUtil.fromJson(strOutTrx, XpcmsrdtO.class);
        return xpcmsrdtO;
    }

    //包装结构体
    public XpcmsrdtI bulidMessage(List<Bis_m_item> bis_m_items, Spc_mfg_data spc_mfg_data) {
        XpcmsrdtI inTrx = new XpcmsrdtI();
        String tool_id = spc_mfg_data.getTool_id();
        List<XpcmsrdtIA> iaryList = new ArrayList<XpcmsrdtIA>();
        for (int i = 0; i < bis_m_items.size(); i++) {
            Bis_m_item bis_m_item = bis_m_items.get(i);
            XpcmsrdtIA iary = new XpcmsrdtIA();
            iary.setData_group(bis_m_item.getData_group());
            iary.setData_value(getDBDataValue(i, spc_mfg_data));//?
            iary.setData_group_seq(bis_m_item.getData_group_seq());
            iaryList.add(iary);
        }
        inTrx.setIary(iaryList);
        inTrx.setTool_id(tool_id);
        return inTrx;
    }

    public XpcmsrdtI bulidMessage2(List<Bis_m_item> bis_m_items, List<String> valueList, String toolId, String mesIdFk) {
        XpcmsrdtI inTrx = new XpcmsrdtI();
        List<XpcmsrdtIA> iaryList = new ArrayList<XpcmsrdtIA>();
        Integer vlsize = valueList.size();
        Integer itemsize = bis_m_items.size();
        /*Integer size = 0;
        if(vlsize <= itemsize){
            size = vlsize;
        }else{
            size = itemsize;
        }*/
        for(int m = 0 ;m < vlsize ;m++){
            if(m >= itemsize){
                break;
            }
            String value = valueList.get(m);
            if (!StringUtils.isEmpty(value)) { //不为空才组结构体
                System.out.println(vlsize);
                System.out.println(itemsize);
                XpcmsrdtIA iary = new XpcmsrdtIA();
                iary.setData_group(bis_m_items.get(m).getData_group());
                iary.setData_value(value);
                iary.setData_group_seq(bis_m_items.get(m).getData_group_seq());
                iaryList.add(iary);
            }
        }

        inTrx.setIary(iaryList);
        inTrx.setTool_id(toolId);
        inTrx.setMes_id_fk(mesIdFk);
        return inTrx;
    }


    public String getDBDataValue(Integer i, Spc_mfg_data spc_mfg_data) {
        String data_value = "";
        String prop = String.format("data_value_%d", i + 1);
        try {
            data_value = BeanUtils.getProperty(spc_mfg_data, prop);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return data_value;
    }

/*    public static void main(String[] args) {
        Spc_ret_mfg_data spc_ret_mfg_data = new Spc_ret_mfg_data();
        spc_ret_mfg_data.setBox_id_fk("box_id");
        try {
            final String box_id_fk = BeanUtils.getProperty(spc_ret_mfg_data, "box_id_fk");
            System.out.println(box_id_fk);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }*/

/*    public void test() {
        Spc_mfg_data spc_mfg_data = new Spc_mfg_data();
        spc_mfg_data.setUnq_seq_id("123");
        spc_mfg_data.setMes_id("test");
        spcMfgDataDao.save(spc_mfg_data);
    }*/

    public void test(){
        // TODO Auto-generated method stub
        File file = new File("E:/TOOL/p170927.d11");
        BufferedReader reader = null;
        String tempString = null;
        int line =1;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            while ((tempString = reader.readLine()) != null) {
                String temp = "";
                String[] tep;
                Spc_mfg_data spc_mfg_data = new Spc_mfg_data();
                if(tempString.contains("O T_Spike Load..Gas")){
                    temp = tempString.substring(41);
                    tep = temp.split("  ");
                    spc_mfg_data.setId(GUIDGenerator.javaGUID());
                    spc_mfg_data.setInput_flg(0);
                    spc_mfg_data.setTool_id("DIF1-1");
                    spc_mfg_data.setMes_id("TEMP");
                    for(int i = 0 ;i < tep.length ;i++){
                        String prop = String.format("data_value_%d", i + 1);
                        try {
                            BeanUtils.setProperty(spc_mfg_data, prop,tep[i]);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                    spcMfgDataDao.save(spc_mfg_data);
                }else if(tempString.contains("ActPwr")){
                    temp = tempString.substring(40);
                    tep = temp.split("  ");
                    spc_mfg_data.setId(GUIDGenerator.javaGUID());
                    spc_mfg_data.setInput_flg(0);
                    spc_mfg_data.setTool_id("DIF1-1");
                    spc_mfg_data.setMes_id("POWR");
                    for(int i = 0 ;i < tep.length ;i++){
                        String prop = String.format("data_value_%d", i + 1);
                        try {
                            BeanUtils.setProperty(spc_mfg_data, prop,tep[i]);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                    spcMfgDataDao.save(spc_mfg_data);
                }else if(tempString.contains("N2,N2-L,O2-H,O2,N2-POCl3:")){
                    temp = tempString.substring(49);
                    tep = temp.split("  ");
                    spc_mfg_data.setId(GUIDGenerator.javaGUID());
                    spc_mfg_data.setInput_flg(0);
                    spc_mfg_data.setTool_id("DIF1-1");
                    spc_mfg_data.setMes_id("FLOW");
                    for(int i = 0 ;i < tep.length ;i++){
                        String prop = String.format("data_value_%d", i + 1);
                        try {
                            BeanUtils.setProperty(spc_mfg_data, prop,tep[i]);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                    spcMfgDataDao.save(spc_mfg_data);
                }else if(tempString.contains("N2Purge")){
                    temp = tempString.substring(57);
                    tep = temp.split("  ");
                    spc_mfg_data.setId(GUIDGenerator.javaGUID());
                    spc_mfg_data.setInput_flg(0);
                    spc_mfg_data.setTool_id("DIF1-1");
                    spc_mfg_data.setMes_id("PRES");
                    for(int i = 0 ;i < tep.length ;i++){
                        String prop = String.format("data_value_%d", i + 1);
                        try {
                            BeanUtils.setProperty(spc_mfg_data, prop,tep[i]);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                    spcMfgDataDao.save(spc_mfg_data);
                }

                System.out.println("Line"+ line + ":" +tempString);
                line ++ ;
            }
            reader.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }





}
